<template>
  <view class="warp">
    <canvas
      canvas-id="hoCanvas"
      class="canvas"
      :style="{ height: lineBgHeight + 'px' }"
    ></canvas>
    <view class="cardBox">
      <view class="cardTop">
        <image :src="img3" mode="widthFix"></image>
		<view class="cardTopBox">
			<image :src="img" mode="widthFix"></image>
		</view>
      </view>
      <view class="cardBottom">
        <view class="content">
          <view class="contentTxt">
			<text>{{user.Name}}</text>
			<text>邀请您一起加入挥友圈～</text>
          </view>
		  <image :src="qr" mode="widthFix"></image>
        </view>
      </view>
    </view>
    <button v-if="btnshow" @click="saveImageToAlbum">保存到相册</button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      user: [],
      btnshow: false,
      show: false,
      img: "../../static/img/test.png",
      qr: "",
      postUrl: "",
      canvasW: "",
      canvasH: "",
      _rpx: "",
      ratio: "",
      windowWidth: "",
      windowHeight: "",
      cW: "",
      cH: "",

      img_w: "",
      img_h: "",

      user_name: "",
      img3: "",
      lineBgHeight: 0,
      sysWidth: "",
      sysHeight: "",
      imageH: "",
    };
  },
  watch: {
    qr: {
      handler(val) {
        console.log(val);
        // this.saveImg();
      },
      immediate: true,
      deep: true,
    },
  },
  async onLoad() {
    uni.getSystemInfo({
      success: (res) => {
        this.cW = res.windowWidth;
        this.cH = res.windowHeight;
      },
    });

    this.img3 =
      "https://wavestation.oss-cn-shenzhen.aliyuncs.com/upload/1718337478173550.png";
  },
  async onReady() {
    await this.getUserInfo();

    await this.CreateShareQR();

    await this.saveImg();
  },
  methods: {
    async getUserInfo() {
      let u = uni.getStorageSync("user");
      console.log(u.UserID);
      let res = await this.$api.post("User/GetUserInfo", {
        ID: u.UserID,
      });

      this.user = res.data;

      this.img = this.user.UserImgs;
      this.user_name = this.user.Name;

      let that = this;
      wx.getImageInfo({
        src: this.img,
        success: function (res) {
          that.img_w = res.width;
          that.img_h = res.height;

          that.ratio = res.width / res.height;
        },
        fail: (res) => {},
      });
    },

    async CreateShareQR() {
      let res = await this.$api.post("Action/CreateShareQR", {
        Page: "pages/tab/home",
      });
      console.log("qr");
      console.log(res);
      this.qr = 'https://wavestation.oss-cn-shenzhen.aliyuncs.com/upload/17188771800961437.png';
    },

    saveImg() {
      var that = this;
      let promise1 = new Promise(function (resolve, reject) {
        console.log("promise1", that.img);
        wx.getImageInfo({
          src: that.img,
          success: function (res) {
            console.log("promise1--", res);
            resolve(res);
          },
          fail: (res) => {
            reject(res);
            console.log("promise1错误");
            console.log(res);
          },
        });
      });
      let promise2 = new Promise(function (resolve, reject) {
        console.log("------");
        console.log("promise2", that.qr);
        wx.getImageInfo({
          src: 'https://wavestation.oss-cn-shenzhen.aliyuncs.com/upload/17188771800961437.png',
          success: function (res) {
            console.log("promise2--", res);
            that.show = true;
            resolve(res);
          },
          fail: (res) => {
            reject(res);
            console.log("promise2错误");
            console.log(res);
          },
        });
      });

      let promise3 = new Promise(function (resolve, reject) {
        wx.getImageInfo({
          src: that.img3,
          success: function (res) {
            console.log("promise3--", res);
            that.show = true;
            resolve(res);
          },
          fail: (res) => {
            reject(res);
            console.log("promise3错误");
            console.log(res);
          },
        });
      });
      let promise4 = new Promise(function (resolve, reject) {
        wx.getImageInfo({
          src: "https://wavestation.oss-cn-shenzhen.aliyuncs.com/upload/1718356707009810.png",
          success: function (res) {
            console.log("promise4--", res);
            resolve(res);
          },
          fail: (res) => {
            reject(res);
            console.log("promise3错误");
            console.log(res);
          },
        });
      });

      // wx.getSystemInfo({
      // 	success: (res) => {
      // 		//that._rpx = res.windowWidth / 375;
      // 		that.ratio = res.windowWidth / res.windowHeight
      // 		// this.windowWidth = res.windowWidth
      // 		// this.windowHeight = res.windowHeight
      // 	},
      // })
      const query = uni.createSelectorQuery();
      query
        .select(".canvas")
        .fields(
          {
            node: true, //指定要获取的属性，这里设置为size: true表示要获取尺寸信息。
            size: true, //在回调函数(res) => {...}中处理查询结果。回调函数会接收一个res参数，其中包含了查询的结果信息。
          },
          (res) => {
            const dpr = wx.getWindowInfo().pixelRatio;
            wx.getSystemInfo({
              success: (res) => {
                this.sysWidth = res.screenWidth;
                this.sysHeight = res.screenHeight;
              },
            });

            // 在回调函数中，通过res.width和res.height获取到查询元素的宽度和高度。
            const imgRatio = Number(that.ratio);

            that.canvasW = 380;
            that.canvasH = 620;
            that.lineBgHeight = that.canvasH;
            console.log(this.canvasW, this.canvasH);

            // 头像宽高
            let imgW = 280
            let imgH = 280/that.ratio
            // 绘制图片：图片居中显示在 canvas 中

            Promise.all([promise2, promise1, promise3, promise4])
              .then((res) => {
                that.show = true;
                wx.showLoading({
                  title: "海报图片生成中...",
                  icon: "loading",
                  duration: 1000,
                });

                /* 图片获取成功才执行后续代码 */
                var canvas = wx.createCanvasContext("hoCanvas");

                // 绘制背景图
                let leftX =
                  (Number(that.canvasW) - Number(that.canvasW / 1.7)) / 2;
                let topY = 80;
                if (res[1].height < 650) {
                  topY =
                    (Number(that.canvasH) - Number(that.canvasH / 1.7)) / 2;
                  topY /= 1.7;
                }

                canvas.drawImage(
                  res[3].path,
                  0,
                  0,
                  that.canvasW,
                  that.canvasH + 50
                );
                canvas.drawImage(
                  res[1].path,
                  50,
                  100,
                  imgW,
                  imgH
                );

                //顶端矩形蒙版
                //canvas.fillStyle='rgba(0, 0, 0, 0.3)';
                //canvas.fillRect(0,0, this.canvasW,60);
                canvas.font = "bold 20px Arial";
                canvas.setFillStyle("#ffffff");
                canvas.setStrokeStyle("#ffffff");
                // canvas.fillText('雪遇', 110, 30);
                canvas.font = "14px Arial";
                canvas.setFillStyle("#dddddd");
                // canvas.fillText('和有趣的人一起组局', 13, 60);
                console.log(res, "###");
                canvas.drawImage(
                  res[2].path,
                  40,
                  40,
                  res[2].width / 1.5,
                  res[2].height / 1.5
                );

                // 绘制活动二维码
                canvas.drawImage(
                  res[0].path,
                  this.canvasW - 120,
                  this.canvasH / 1.2 - 20,
                  80,
                  80
                );

                canvas.font = "bold 22px Arial";
                canvas.setFillStyle("#333333");
                canvas.setStrokeStyle("#333333");
                let userName = that.$util.entitiesToUtf16(that.user_name);
                canvas.fillText(userName, 40, this.canvasH / 1.2);
                canvas.font = "18px Arial";
                canvas.setFillStyle("#666666");
                canvas.fillText("邀请您一起加入挥友", 40, this.canvasH / 1.1);

                canvas.scale(2, 2);

                canvas.draw();

                setTimeout(function () {
                  wx.canvasToTempFilePath({
                    x: 0,
                    y: 0,
                    width: that.canvasW,
                    height: that.canvasH,
                    destWidth: that.canvasW,
                    destHeight: that.canvasH,
                    canvasId: "hoCanvas",
                    success: function (res) {
                      that.postUrl = res.tempFilePath;
                      // that.saveImageToAlbum();
                      that.btnshow = true;
                      wx.hideLoading();
                    },
                    fail: function (res) {},
                  });
                }, 500);
              })
              .catch((err) => {
                console.dir("出错了", err);
                console.log(err);
                uni.showModal({
                  title: "异常错误",
                  content: "图片生成失败!!!\n[QRError:Damaged QR code]",
                  showCancel: false,
                  success: (res) => {
                    if (res.confirm) uni.navigateBack();
                  },
                });
              });
          }
        )
        .exec();
    },

    saveImageToAlbum: function () {
      var that = this;
      //将图片保存到相册
      wx.saveImageToPhotosAlbum({
        filePath: that.postUrl,
        success(res) {
          wx.showModal({
            title: "保存成功",
            content: "图片成功保存到相册了，快去分享朋友圈吧",
            showCancel: false,
            confirmText: "好的",
            confirmColor: "#818FFB",
            success: function (res) {
              if (res.confirm) {
              }
              // that.hideShareImg()
            },
          });
        },
      });
    },
  },
};
</script>

<style lang="scss">
page {
  background: linear-gradient(to bottom, #9990fe, #8186fe);
}
.warp {
  width: 100%;
//   height: 100vh;
  box-sizing: border-box;
  padding-bottom: 160rpx;
}

.canvas {
  width: 96vw;
  height: 100vh;
  margin: 50rpx auto;
  margin-bottom: 0;
  box-sizing: border-box;
  position: fixed;
  left: -100vw;
}

.height70 {
  height: 70vh;
}

.height100 {
  height: 100vh;
}

.height64 {
  height: 62vh;
}

button {
  position: fixed;
  left: 50%;
  bottom: 80rpx;
  transform: translate(-50%, -50%);
  background-color: #fff;
  color: #706eee;
  border-radius: 16rpx;
  width: 90vw;
  margin: 0 auto;
}

.cardBox{
	width: 100vw;
	background-image: url("https://wavestation.oss-cn-shenzhen.aliyuncs.com/upload/1718356707009810.png");
	background-size: 100% 100%;
	background-repeat: no-repeat;
	display: flex;
	flex-direction: column;
	position: relative;
	.cardTop{
		width: 80%;
		margin: 0 auto;
		padding: 0 10rpx;
		padding-bottom: 35vh;
		

		>image:first-child{
			width: 150rpx;
			margin-top: 70rpx;
		}
		.cardTopBox{
			border-radius: 16rpx;
      display: flex;
      justify-content: center;
			>image{
				width: 90%;
			}
		}
		
	}
	.cardBottom{
		position: absolute;
		bottom: 10vh;
		left: 50%;
		transform: translateX(-50%);
		width:80%;
		height: 15%;
		padding: 0 10rpx;
		margin: 0 auto;
		.content{
			display: flex;
			justify-content: space-between;
			align-items: center;
			.contentTxt{
				display: flex;
				flex-direction: column;
				font-weight: normal;
				text-align: left;
				white-space: nowrap;
				overflow-wrap: break-word;
				>text:first-child{
					color: rgba(51,51,51,1);
					font-size: 42rpx;
					font-weight: 600;
				}
				>text:last-child{
					color: rgba(102,102,102,1);
					font-size: 34rpx;
					margin-top: 20rpx;
				}
			}
			>image{
				width: 152rpx;
			}
		}
	}
}
</style>